const scan = {
  state: {
    printDevice:{}, // 蓝牙id
    printStatus:2,

    scanCodes: JSON.parse(uni.getStorageSync('scanCodes') || '{}'),
    scanInfos: JSON.parse(uni.getStorageSync('scanInfos') || '{}')
  },
  getters:{
    printDevice: state => state.printDevice,
    printStatus: state => state.printStatus,
    scanCodes: state => state.scanCodes,
    scanInfos: state => state.scanInfos
  },
  mutations: {
    SET_SCAN_INFO: (state, data) => {
      const {pageKey,code,info,type} = data || {}
      if(type == 'allClear'){
        state.scanCodes = {}
        state.scanInfos = {}
      }else{
        if(pageKey){
          if(!state.scanCodes[pageKey]){
            state.scanCodes[pageKey] = []
          }
          if(!state.scanInfos[pageKey]){
            state.scanInfos[pageKey] = {}
          }
          if(type == 'clear'){
            state.scanCodes[pageKey] = []
            state.scanInfos[pageKey] = {}
          }else{
            if(code){
              const codes = Array.isArray(code)?code:[code]
              const infos = !info?[]:Array.isArray(info)?info:[info]
              codes.map((item)=>{
                const curIndex = state.scanCodes[pageKey].findIndex((cItem)=> item === cItem)
                if(type == 'del' && curIndex > -1){
                  state.scanCodes[pageKey].splice(curIndex,1)
                }else{
                  if(curIndex == -1){
                    state.scanCodes[pageKey] = [].concat([item],state.scanCodes[pageKey])
                  }else{
                    if(!info){
                      throw Error(JSON.stringify({success:false,message:'您已添加,请勿重复添加'}))
                    }
                  }
                }
                const curInfo = infos.find((cItem)=> (cItem.code || cItem.goods_no) === item)
                if(curInfo && Object.keys(curInfo ||{}).length){
                  state.scanInfos[pageKey][item] = curInfo
                }
              })
            }
          }
        }
      }
      uni.setStorageSync('scanCodes', JSON.stringify(state.scanCodes))
      uni.setStorageSync('scanInfos', JSON.stringify(state.scanInfos))
    },
    SET_PRINT_DEVICE:(state, data) => {
      state.printDevice = data || {}
    },
    SET_PRINT_STATUS:(state, data) => {
      state.printStatus = (data || data === 0)? data: 2
    },
  },

  actions: {
    async setScanCode({ commit },data) {
      try {
        await commit('SET_SCAN_INFO',data)
        return {success:true,message:'操作成功'}
      } catch (error) {
        const errInfo = JSON.parse(error?.message || '{}')
        return errInfo
      }
    }
  }
}

export default scan
